package cn.bluemobi.dylan.step.moder.http.interceptor;

import android.provider.Settings;


import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.TreeMap;

import cn.bluemobi.dylan.step.app.App;
import cn.bluemobi.dylan.step.utils.common.Encrypt;
import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.MultipartBody;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.Buffer;

/**
 * Created by $Liudan on 2018/7/4 0004.
 */
public class CommonParamInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
//        LogUtils.debug(this.getClass().getName(), "ppppppppppppppppppppppppppppppppp==intercept");
        Request request = chain.request();
        request = addPostBaseParams(request);
        return chain.proceed(request);
    }

    /**
     * 添加POST方法基础参数
     *
     * @param request
     * @return
     */
    private Request addPostBaseParams(Request request) {
        FormBody.Builder formBodyBuilder = new FormBody.Builder();  //新建一个构造器
        Map<String, Object> paramMap = new TreeMap<>();
        if (request.body() instanceof FormBody) {
            FormBody formBody = (FormBody) request.body();
//            FormBody.Builder formBodyBuilder = new FormBody.Builder();  //新建一个构造器
            //把原来的参数添加到新的构造器
            for (int i = 0; i < formBody.size(); i++) {
                try {
                    String value = URLDecoder.decode(formBody.encodedValue(i), "UTF-8");  //utf-8编码后 进行解码中文
                    formBodyBuilder.addEncoded(formBody.encodedName(i), value);
                    paramMap.put(formBody.encodedName(i), value);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        } else if(request.body() instanceof MultipartBody){  //文件上传参数
            return  request;
//            MultipartBody.Builder multipartBodybuilder = new MultipartBody.Builder();
////            multipartBodybuilder.setType(MediaType.parse("multipart/form-data"));
//            multipartBodybuilder.setType(MediaType.parse("multipart/mixed"));
////            MultipartBody.Builder multipartBodybuilder = new MultipartBody.Builder().setType(MultipartBody.FORM);
//            MultipartBody partBody = (MultipartBody) request.body();
//            for (int i = 0; i < partBody.size(); i++) {
//                MultipartBody.Part part = partBody.part(i);
//                multipartBodybuilder.addPart(part);
//                MediaType mediaType = part.body().contentType();
//                if (mediaType == null) {
//                    String normalParamKey;
//                    String normalParamValue;
//                    try {
//                        normalParamValue = getParamContent(partBody.part(i).body());
//                        Headers headers = part.headers();
//                        if (!TextUtils.isEmpty(normalParamValue) && headers != null) {
//                            for (String name : headers.names()) {
//                                String headerContent = headers.get(name);
//                                if (!TextUtils.isEmpty(headerContent)) {
//                                    String[] normalParamKeyContainer = headerContent.split("name=\"");
//                                    if (normalParamKeyContainer.length == 2) {
//                                        normalParamKey = normalParamKeyContainer[1].split("\"")[0];
////                                        signParams.put(normalParamKey, normalParamKey);
//                                        paramMap.put(normalParamKey, normalParamKey);
//                                        break;
//                                    }
//                                }
//                            }
//                        }
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
//                }
//
//            }
//            String rank = rank();
//            multipartBodybuilder.addFormDataPart("rank", rank);//此处添加apptoken参数
//            paramMap.put("rank", rank);
//            //设备ID
//            String ANDROID_ID = Settings.System.getString(App.getInstance().getContentResolver(), Settings.System.ANDROID_ID);
//            multipartBodybuilder.addFormDataPart("client_code", ANDROID_ID);
//            paramMap.put("client_code", ANDROID_ID);
//
//            multipartBodybuilder.addFormDataPart("client_sign", clientSign(paramMap));
//
////            request = request.newBuilder().post(multipartBodybuilder.build()).build();
//            request = request.newBuilder().method(request.method(), multipartBodybuilder.build()).build();
//            return request;

        }

        String rank = rank();
        formBodyBuilder.addEncoded("rank", rank);//此处添加apptoken参数
        paramMap.put("rank", rank);
        //设备ID
        String ANDROID_ID = Settings.System.getString(App.getInstance().getContentResolver(), Settings.System.ANDROID_ID);
        formBodyBuilder.addEncoded("client_code", ANDROID_ID);
        paramMap.put("client_code", ANDROID_ID);

//            User user = RHutil.getUser();
//            if(user!=null && user.token!=null){
//                formBodyBuilder.addEncoded("token", user.token);//此处添加apptoken参数
//                paramMap.put("token", user.token);
//            }
        formBodyBuilder.addEncoded("client_sign", clientSign(paramMap));

        request = request.newBuilder().post(formBodyBuilder.build()).build();
        return request;
    }

    /**
     * 获取常规post请求参数
     */
    private String getParamContent(RequestBody body) throws IOException {
        Buffer buffer = new Buffer();
        body.writeTo(buffer);
        return buffer.readUtf8();
    }


    /**
     * 添加GET方法基础参数
     *
     * @param request
     * @return
     */
    private Request addGetBaseParams(Request request) {
        String rank = rank();
        HttpUrl httpUrl = request.url()
                .newBuilder()
                .addQueryParameter("rank", rank) //添加随机数
                .build();

        sign(httpUrl);
        request = request.newBuilder().url(httpUrl).build();

        return request;
    }


    /**
     * 添加签名
     *
     * @param httpUrl get
     */
    private void sign(HttpUrl httpUrl) {
        Set<String> nameSet = httpUrl.queryParameterNames();
        ArrayList<String> nameList = new ArrayList<>();
        nameList.addAll(nameSet);
        Map<String, Object> paramMap = new HashMap<>();
        for (int i = 0; i < nameList.size(); i++) {
            paramMap.put(nameList.get(i), httpUrl.queryParameterValue(i));
        }
        httpUrl.newBuilder().addQueryParameter("client_sign", clientSign(paramMap)).build();
    }

    private String rank() {
        Random rnd = new Random();
        int rndint = rnd.nextInt(10000);
        return rndint + "";
    }

    public String clientSign(Map<String, Object> parameterMap) {
        String sign = getAccess_token(parameterMap);

        String encryptSign = Encrypt.shaEncrypt(Encrypt.md5(sign + "skGh34sdj"));
        return encryptSign.substring(2, 26);
    }

    public static String getAccess_token(Map<String, Object> parameterMap) {

        StringBuffer stringBuffer = new StringBuffer();
        if (parameterMap != null) {
            Iterator it = parameterMap.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry entry = (Map.Entry) it.next();
                stringBuffer.append(entry.getKey());
                stringBuffer.append(entry.getValue());
            }
        }
        return stringBuffer.toString();
    }

}